<?php
declare (strict_types=1);

namespace app\common\model;

use app\exception\TokenException;
use app\exception\UserException;
use think\facade\Cache;
use think\Model;

/**
 * @mixin \think\Model
 */
class Admin extends Model
{

    //
    public static function login($username, $password)
    {
        $admin = self::where('user_name', $username)
            ->find();
        if (empty($admin)) {
            throw new UserException('用户不存在');
        }
        $encrypt_password = md5($password);
        if ($admin->password != $encrypt_password) {
            throw new UserException('密码错误');
        }
        $admin->login_ip = get_request_ip();
        $admin->login_date = now_date();
        if ($admin->save()) {
            $token = $admin->getToken();
            if (config('self.site_one') == 1) {
                $admin_key = RedisKey::getAdminKey($admin->id);
                Cache::store('redis')->set($admin_key, $token);
            }
            return $token;
        } else {
            throw new UserException('登录失败');
        }
    }


    /**
     * 获取登录token
     */
    public function getToken()
    {
        $user_data = [
            'admin_id' => $this->id,
            'password' => $this->password,
            'login_date' => $this->login_date,
            'login_ip' => $this->login_ip
        ];
        return aes_encrypt(json_encode($user_data));
    }

    public static function checkAuthorization($token): Admin
    {
        if (empty($token)) {
            throw new TokenException('登录异常，请重新登录');
        }
        $admin_info = json_decode(aes_decrypt($token), true);
        $admin = self::where("id", $admin_info['admin_id'])->find();
        //是否开启单设备登录验证
        if (config('self.site_one') == 1) {
            $admin_key = RedisKey::getAdminKey($admin->id);
            if (!Cache::store('redis')->has($admin_key))
                throw new TokenException('登录状态异常');
            $admin_token = Cache::store('redis')->get($admin_key);
            if ($token != $admin_token)
                throw new TokenException('您已在其他设备登录');
        }
        if ($admin_info['password'] != $admin->password)
            throw new TokenException('登录过期');
        return $admin;
    }
}
